#include "lock.h"
#include "sched.h"
#include "syscall.h"

void spin_lock_init(spin_lock_t *lock)
{
    lock->status = UNLOCKED;
}

void spin_lock_acquire(spin_lock_t *lock)
{
    while (LOCKED == lock->status)
    {
    };
    lock->status = LOCKED;
}

void spin_lock_release(spin_lock_t *lock)
{
    lock->status = UNLOCKED;
}

void do_mutex_lock_init(mutex_lock_t *lock)
{
    lock->status = UNLOCKED;
    lock->holder = -1;
    queue_init(&(lock->wait_queue));
}

void do_mutex_lock_acquire(mutex_lock_t *lock)
{
    if(lock->status == LOCKED){
        //do_block(&block_queue);
        do_block(&(lock->wait_queue));
    }
    else {
        lock->status = LOCKED;
        lock->holder = current_running->pid;
    }
}

void do_mutex_lock_release(mutex_lock_t *lock)
{
    if(!queue_is_empty(&(lock->wait_queue))){
        lock->holder = ((pcb_t*)lock->wait_queue.head)->pid;
        do_unblock_one(&(lock->wait_queue));
        lock->status = LOCKED;
    }
    else {
        lock->status = UNLOCKED;
    }
}
